package com.shakespace.artofandroid.chapter02.socket

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.util.Log
import com.shakespace.firstlinecode.global.TAG
import java.io.*
import java.net.ServerSocket
import java.net.Socket

class TCPService : Service() {

    private var isServiceDestoryed = false

    // use ctrl+ command + space to input emoji😀
    private val autoReplyWords = arrayListOf(
        "Hello \uD83D\uDE00",
        "My name is xxx , and you \uD83D\uDE03 ",
        "It is a nice day today \uD83D\uDE02",
        "I am not a real man",
        "\uD83D\uDE05",
        "\uD83D\uDE06",
        "\uD83D\uDE01"
    )


    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    override fun onCreate() {
        super.onCreate()
        Thread(TcpServer()).start()
    }

    inner class TcpServer : Runnable {
        override fun run() {
            val serverSocket: ServerSocket?

            try {
                serverSocket = ServerSocket(8600)
            } catch (e: Exception) {
                Log.e(this.TAG, "run: ${e.localizedMessage}")
                return
            }
            try {
                while (!isServiceDestoryed) {
                    val client = serverSocket.accept()
                    Thread {
                        responsableClient(client)
                    }.start()
                }
            } catch (e: Exception) {
                Log.e(this.TAG, "run: ${e.localizedMessage}")
            }

        }
    }

    private fun responsableClient(client: Socket?) {
        client?.apply {
            // use for receiving
            val inputStream = BufferedReader(InputStreamReader(this.getInputStream()))
            // use for replying
            val outWriter = PrintWriter(BufferedWriter(OutputStreamWriter(client.getOutputStream())), true)

            outWriter.println("welcome to chat room")
            while (!isServiceDestoryed) {
                val line = inputStream.readLine()
                Log.e(this.TAG, "responsableClient: msg from client + $line")
                if (line.isNullOrEmpty()) {
                    break
                }

                // reply in random
                val random = (0 until autoReplyWords.size).random()
                outWriter.println(autoReplyWords[random])
                Log.e(this.TAG, "responsableClient:  out  ${autoReplyWords[random]}")
            }
            try {
                inputStream.close()
                outWriter.close()
            } catch (e: Exception) {
                Log.e(this.TAG, "responsableClient: ${e.localizedMessage}")
            }
            client.close()
        }
    }

    override fun onDestroy() {
        Log.e(this.TAG, "onDestroy: service stop ")
        isServiceDestoryed = true
        super.onDestroy()
    }
}
